import { ref } from 'vue';
import api from 'axios';
import { menuItem, menuTreeItem } from 'stores/model';
import { sysBaseVOAPI } from 'src/util/SysBaseConst';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';

export function getPermissionMenuTree () {
  //消息通知hook
  const {
    showMessage
  } = useMessageNotify();

  //存储数据数组
  let arrList: menuItem[] = [];
  let mTree = ref<menuTreeItem[]>(<menuTreeItem[]>[]);


  //*****************************************************************************************
  //
  //          权限配置中显示菜单树{id, label}
  //
  //*****************************************************************************************

  //生产权限菜单树
  const producePermissionMenuTree = (ml: menuItem[]): menuTreeItem[] => {
    let list: menuTreeItem[] = [];

    //递归函数
    const filterTree = (ls: menuItem[], arr: menuTreeItem[]) => {
      ls.forEach((item: menuItem) => {
        let el = [] as menuTreeItem[];

        //先生产子节点
        if (item.children && item.children.length > 0) {
          filterTree(item.children, el);
        }

        //生成完整节点
        arr.push({
          id: item.id,
          label: item.label,
          children: el
        });
      })
    };

    //调用递归函数
    filterTree(ml, list);

    return list;
  }

  //快速检索菜单树,根据id查询label
  const searchPermissionMenuTreeVO = (mtr: menuTreeItem[], id: number): string | null => {
    let name = null;
    let isFind = false;

    //检索函数
    const searchByParams = (arr: menuTreeItem[], id: number) => {
      for (let i = 0; i < arr.length; i++) {
        if ((arr[i].children) && (arr[i].children.length > 0)) {
          let list = arr[i].children;
          searchByParams(list, id);
        }

        //已经找到，且值已储存胡到name中去
        if (isFind) {
          break;
        }

        //找到，当前值满足条件
        if (arr[i].id === id) {
          isFind = true;
          name = arr[i].label;
          break;
        }
      }
    }

    //朝招函数
    searchByParams(mtr, id);
    return name;
  }

  //读取菜单数据
  const getPermissionMenuTreeVO = () => {
    api.post(sysBaseVOAPI.MENU_VO_TREE).then((res: any) => {
      if (res.data.message === 'Success') {
        arrList.length = 0;
        arrList = res.data.data;
        //console.log(arrList);

        mTree.value.length = 0;
        mTree.value = producePermissionMenuTree(arrList);
      } else {
        showMessage(res.data.message);
      }
    }).catch((error: any) => {
      showMessage(error.message);
    });
  }

  return {
    arrList,
    mTree,
    getPermissionMenuTreeVO,
    searchPermissionMenuTreeVO
  }
}
